<template>
  <div class="flex-row autoGrow replyContainer">
    <choose-service-account
      :multiple="false"
      @serviceChange="serviceChange"
    >
       <div class="autoGrow welcomeOptions flex-column">
        <div class="toggleOwner">
          <label>
            <input type="radio"
            name="manager"
            value="manager"
            @change="changeGroupType"
            :checked="groupType=='manager'"> 群主
          </label>
          <label>
            <input type="radio"
            name="manager"
            value="member"
            @change="changeGroupType"
            :checked="groupType=='member'"> 非群主
          </label>
          
        </div>
        <search placeholder="请输入关键词" @change="changeSearch"></search>
        <div class="groupListTitle">
          <label><input type="checkbox" v-model="selectAll"> 群（{{checkedGroups.length}}/{{groups ? groups.length : 0}})</label>
        </div>
        <div class="groupList autoGrow">
           <label v-for="(group) in filterGroups" :key="group.id">
            <user-list-item
              :showBadge="false"
              :showLastMessage="false"
              currentUserWxid=""
              :item="group">
              <template v-slot:checkbox>
                <input type="checkbox"
                  :checked="checkedGroups.includes(group.wxid)"
                  :disabled="hasSetingGroups.includes(group.id) && !editSetingGroups.includes(group.id)"
                  class="select"
                  @change="toggleSelect(group)">
              </template>
              <template v-slot:bottomInfo>
                <div>
                  <span>群成员{{group.personnum}} </span>
                  <span>非好友{{group.personnum - group.friendNum}}</span>
                </div>
              </template>
              <template v-slot:attachInfo>
                <div class="fontGrey">
                  {{hasSetingGroups.includes(group.id) ? '已设置' : ''}}
                </div>
              </template>
            </user-list-item>
          </label>
        </div>
      </div>
    </choose-service-account>
    <div class="settingOption flex-column">
      <div class="subTitle">标签设置</div>
      <div class="option flex-row">
        <span>标签</span>
        <input type="text" class="layui-input" v-model="curLabel">
        <button class="layui-btn layui-btn-xs" @click="addLabel">添加</button>
      </div>
      <div class="labels felx-row">
        <span class="layui-badge layui-bg-blue" v-for="(label, i) in labels" :key="i">{{label}}</span>
      </div>
      <div class="submit flex-row">
        <button class="layui-btn layui-btn-sm" @click="submitLabel">提交</button>
      </div>
    </div>
    <div class="welcomeList flex-column autoGrow">
      <div class="subTitle">标签记录</div>
      <div class="listContainer autoGrow">
        <div
          class="recordItem flex-column"
          :key="index"
          v-for="(record, index) in welcomeList">
          <div class="recordItemInfo flex-row">
            <img :src="service&&service.avatar" alt="">
            <div class="serviceInfo flex-column">
              <div class="flex-row serviceInfoDetail">
                <div class="serviceName">{{service&&service.nick}}</div>
              </div>
              <div class="fontGrey sendTyeInfo">
                {{ formatTime(record.createTime||new Date())+' 配置了'+ record.groupList.length +'个群' }}
              </div>
            </div>
            <div class="labels flex-row autoGrow">
              <button
                @click="deleteRecord(record, index)"
                class="layui-btn layui-btn-danger layui-btn-xs">
                删除
              </button>
            </div>
          </div>
          <div class="targetsOperate flex-row">
            <button
                @click="toggleDetail(index)"
                class="layui-btn layui-btn-warm layui-btn-xs">
                {{ record.showDetail ? '收起' : '详细' }}
            </button>
          </div>
          <div class="recordDetail flex-column" v-if="record.showDetail">
            <div class="tabs">
              <button
                  :class="['layui-btn','layui-btn-xs']">
                  设置群
              </button>
            </div>
            <div class="flex-column targetsList">
              <div class="labels">
                 <span class="layui-badge layui-bg-blue" v-for="(label, i) in record.tagname.split(',')" :key="i">{{label}}</span>
              </div>
              <div style="    flex-flow: row wrap; align-content: flex-start; display: inline-flex;">
                <div class="listItem flex-row" v-for="(target) in record.groupList" :key="target.id">
                  <img :src="target.avatar" alt="" class="listItemAvatar">
                  <div class="listItemInfo flex-column">
                    <div class="listItemTopInfo flex-row">
                      <div class="listItemName textEllipsis">{{ target.groupname||'聊天群' }}</div>
                      </div>
                      <div class="listItemBottomInfo flex-row fontGrey">
                        <span>群成员{{target.personnum}} 非好友{{target.personnum-target.friendNum}}</span></div>
                        </div>
                </div>
               </div>

            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import ChooseServiceAccount from '@/components/chooseServiceAccount'
import UserListItem from '@/components/userListItem'
import QuickReplies from './quickReplies'
import Search from '@/components/search'
import pinyin from '@/lib/pinyin'

export default {
  name: 'tag',
  data() {
    return {
      currentRecord: null,
      service: null,
      selectAll: false,
      groups: [],
      keyword: '',
      groupType: 'manager', // member
      welcomeName: '',
      curLabel: '',
      reply: '',
      labels: [],
      welcomeList: [],
      keywords: [''],

      checkedGroups: [], // 等待选择的群组
      hasSetingGroups:[], // 已经设置的群组
      editSetingGroups:[] // 已经设置但可编辑群组
    }
  },
  components: {
    ChooseServiceAccount,
    UserListItem,
    QuickReplies,
    Search
  },
  methods: {
    serviceChange(services) {
      this.service = services[0]
      this.init()
    },
    init() {
      this.$api.group.list({
        csid: this.service.csid,
        wxaccount: this.service.wxid
      }).then(data=>{
        this.groups = this.transGroupData(data);
      }).catch(e=>this.$msg(e))
      this.$api.tag.list({
        csId: this.service.csid,
        wxAccount: this.service.wxid
      }).then(data=>{
        this.welcomeList = data
      }).catch(e=>this.$msg(e))
    },
    changeGroupType(e) {
      this.groupType = e.target.value
    },
    toggleSelect(group) {
      if (this.checkedGroups.includes(group.wxid)) {
        this.checkedGroups = this.checkedGroups.filter(item=>{
          return item!=group.wxid
        })
      } else {
        this.checkedGroups.push(group.wxid)
      }
    },
    changeSearch(val) {
      this.keyword = val
    },
    settingReply(reply) {
      this.reply = reply
    },
    deleteRecord(record, i) {
      this.$api.tag.delete({
        csId: this.service.csid,
        wxAccount: this.service.wxid,
        id: record.id
      }).then(()=>{
        this.welcomeList.splice(i, 1)
      }).catch(e=>this.$msg(e))
    },
    toggleDetail(index) {
      const record = this.welcomeList[index];
      this.$set(this.welcomeList, index, {
        ...record,
        showDetail: !record.showDetail
      })
    },
    changeKeyword(index, e) {
      this.$set(this.keywords, index, e.target.value)
    },
    addLabel() {
      if (this.curLabel) {
        this.labels.push(this.curLabel)
        this.curLabel = ''
      }
    },
    submitLabel() {
      if (!this.service) return this.$msg("请选择客服账号")
      if (!this.checkedGroups.length) return this.$msg("请选择要设置的群")
      if (!this.labels.length) return this.$msg("请添加标签")
      const groups = this.groups.filter(item=> this.checkedGroups.includes(item.id))

      this.$api.tag.insert({
        groupNoList: groups.map(g=>g.groupno),
        csId: this.service.csid,
        wxAccount: this.service.wxid,
        tagName: this.labels.join(",")
      }).then(rs=>{
        this.welcomeList.unshift(rs)
        this.$msg('添加成功')
      }).catch(e=>this.$msg(e))
    }
  },
  computed: {
    filterGroups(){
      const isShowManager = this.groupType === 'manager'
      const keyword = pinyin.getFullChars(this.keyword).toLocaleLowerCase() 

      return this.groups.filter(item=>{
        const chars = pinyin.getFullChars(item.groupname).toLocaleLowerCase() ;
        if(isShowManager){
          return item.isfirst === 1 && chars.indexOf(keyword)>-1
        }else{
          return item.isfirst !== 1 && chars.indexOf(keyword)>-1
        }
         
      })
      
    },
  },
  watch: {
    selectAll(val) {
      if (val) {
        this.checkedGroups = this.groups.map(g=>g.wxid)
      } else {
        this.checkedGroups = []
      }
    },
  }
}
</script>
<style scoped>
.listItem{
  flex: 0 0 33%
}
</style>